package com.hz.interceptors;

import com.hz.utils.JwtUtil;
import com.hz.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        // 验证请求头中的token
        try {
            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            String s = ops.get(token);
            if (s==null){
                // token失效
                throw new RuntimeException("请重新登录");
            }
            Map<String,Object> claims = JwtUtil.parseToken(token);
            // 存入ThreadLocal
            ThreadLocalUtil.set(claims);
        } catch (Exception e) {
            response.setStatus(401);
            // 不放行
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 一次请求结束后  移除token 防止内存泄露
        ThreadLocalUtil.remove();
    }
}
